using System;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WeChatFileManagementWinApp
{
    /// <summary>
    /// 文件操作工具类，提供常用的文件操作方法
    /// </summary>
    public static class FileOperationHelper
    {
        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern bool SHObjectProperties(IntPtr hwnd, uint shopObjectType, string pszObjectName, string pszPropertyPage);

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool DestroyIcon(IntPtr hIcon);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }

        private const uint SHGFI_ICON = 0x000000100;
        private const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;
        private const uint SHGFI_SMALLICON = 0x000000001;
        private const uint SHGFI_LARGEICON = 0x000000000;
        private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
        private const uint SHOP_FILEPATH = 0x00000002;
        private const int SW_SHOW = 5;

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否成功打开</returns>
        public static bool OpenFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                MessageBox.Show("文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            try
            {
                ShellExecute(IntPtr.Zero, "open", filePath, null, Path.GetDirectoryName(filePath), SW_SHOW);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 打开文件所在文件夹
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否成功打开</returns>
        public static bool OpenFileLocation(string filePath)
        {
            if (!File.Exists(filePath))
            {
                MessageBox.Show("文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            try
            {
                string directory = Path.GetDirectoryName(filePath);
                ShellExecute(IntPtr.Zero, "explore", directory, null, null, SW_SHOW);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开文件夹失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 显示文件属性对话框
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否成功显示</returns>
        public static bool ShowFileProperties(string filePath)
        {
            if (!File.Exists(filePath))
            {
                MessageBox.Show("文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            try
            {
                return SHObjectProperties(IntPtr.Zero, SHOP_FILEPATH, filePath, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"显示文件属性失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 复制文件到剪贴板
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否成功复制</returns>
        public static bool CopyFileToClipboard(string filePath)
        {
            if (!File.Exists(filePath))
            {
                MessageBox.Show("文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            try
            {
                var fileList = new StringCollection();
                fileList.Add(filePath);
                Clipboard.SetFileDropList(fileList);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 复制文件名到剪贴板
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否成功复制</returns>
        public static bool CopyFileNameToClipboard(string filePath)
        {
            try
            {
                string fileName = Path.GetFileName(filePath);
                Clipboard.SetText(fileName);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制文件名失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 复制文件路径到剪贴板
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否成功复制</returns>
        public static bool CopyFilePathToClipboard(string filePath)
        {
            try
            {
                Clipboard.SetText(filePath);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制文件路径失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否成功删除</returns>
        public static bool DeleteFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                MessageBox.Show("文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            try
            {
                var result = MessageBox.Show(
                    "确定要删除这个文件吗？此操作不可恢复。",
                    "确认删除",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning
                );

                if (result == DialogResult.Yes)
                {
                    File.Delete(filePath);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 获取文件图标
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="extension">文件扩展名（当文件不存在时使用）</param>
        /// <returns>文件图标</returns>
        public static Image GetFileIcon(string filePath, string extension = null)
        {
            SHFILEINFO shfi = new SHFILEINFO();
            uint flags = SHGFI_ICON | SHGFI_SMALLICON;

            try
            {
                // 如果文件不存在，使用扩展名获取图标
                if (!File.Exists(filePath) && !string.IsNullOrEmpty(extension))
                {
                    flags |= SHGFI_USEFILEATTRIBUTES;
                    filePath = extension;
                }

                IntPtr result = SHGetFileInfo(filePath, FILE_ATTRIBUTE_NORMAL, ref shfi, (uint)Marshal.SizeOf(shfi), flags);

                if (result != IntPtr.Zero && shfi.hIcon != IntPtr.Zero)
                {
                    try
                    {
                        using (Icon icon = Icon.FromHandle(shfi.hIcon))
                        {
                            // 创建一个新的Bitmap来保存图标
                            Bitmap bitmap = new Bitmap(icon.Width, icon.Height);
                            using (Graphics g = Graphics.FromImage(bitmap))
                            {
                                g.DrawIcon(icon, 0, 0);
                            }
                            return bitmap;
                        }
                    }
                    finally
                    {
                        // 确保释放图标句柄
                        DestroyIcon(shfi.hIcon);
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误但不抛出异常
                System.Diagnostics.Debug.WriteLine($"获取图标失败: {ex.Message}");
            }

            // 如果获取图标失败，返回默认图标
            try
            {
                using (Icon defaultIcon = SystemIcons.Application)
                {
                    Bitmap bitmap = new Bitmap(defaultIcon.Width, defaultIcon.Height);
                    using (Graphics g = Graphics.FromImage(bitmap))
                    {
                        g.DrawIcon(defaultIcon, 0, 0);
                    }
                    return bitmap;
                }
            }
            catch
            {
                // 如果连默认图标都无法创建，返回一个1x1的透明位图
                return new Bitmap(1, 1);
            }
        }
    }
} 